{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Web Devs Quickstart\n",
    "\n",
    "> A fast introduction to FastHTML for experienced web developers.\n",
    "\n",
    "- order: 3"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#| hide\n",
    "from nbdev.showdoc import *"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Installation"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "```bash\n",
    "pip install python-fasthtml\n",
    "````"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## A Minimal Application"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A minimal FastHTML application looks something like this:\n",
    "\n",
    "``` {.python filename=\"main.py\" code-line-numbers=\"true\"}\n",
    "from fasthtml.common import *  # <1>\n",
    "\n",
    "app, rt = fast_app()  # <2>\n",
    "\n",
    "@rt(\"/\")  # <3>\n",
    "def get():  # <4>\n",
    "    return Titled(\"FastHTML\", P(\"Let's do this!\"))  # <5>\n",
    "\n",
    "serve()  # <6>\n",
    "```\n",
    "\n",
    "1. We import what we need for rapid development! A carefully-curated set of FastHTML functions and other Python objects is brought into our global namespace for convenience.\n",
    "2. We instantiate a FastHTML app with the `fast_app()` utility function. This provides a number of really useful defaults that we'll take advantage of later in the tutorial. \n",
    "3. We use the `rt()` decorator to tell FastHTML what to return when a user visits `/` in their browser.\n",
    "4. We connect this route to HTTP GET requests by defining a view function called `get()`.\n",
    "5. A tree of Python function calls that return all the HTML required to write a properly formed web page. You'll soon see the power of this approach.\n",
    "6. The `serve()` utility configures and runs FastHTML using a library called `uvicorn`.\n",
    "\n",
    "Run the code:\n",
    "\n",
    "```bash\n",
    "python main.py\n",
    "```\n",
    "\n",
    "The terminal will look like this:\n",
    "\n",
    "```bash\n",
    "INFO:     Uvicorn running on http://0.0.0.0:5001 (Press CTRL+C to quit)\n",
    "INFO:     Started reloader process [58058] using WatchFiles\n",
    "INFO:     Started server process [58060]\n",
    "INFO:     Waiting for application startup.\n",
    "INFO:     Application startup complete.\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Confirm FastHTML is running by opening your web browser to [127.0.0.1:5001](http://127.0.0.1:5001). You should see something like the image below:\n",
    "\n",
    "![](quickstart-web-dev/quickstart-fasthtml.png)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "::: {.callout-note}\n",
    "While some linters and developers will complain about the wildcard import, it is by design here and perfectly safe. FastHTML is very deliberate about the objects it exports in `fasthtml.common`. If it bothers you, you can import the objects you need individually, though it will make the code more verbose and less readable.\n",
    "\n",
    "If you want to learn more about how FastHTML handles imports, we cover that [here](https://www.fastht.ml/docs/explains/faq.html#why-use-import).\n",
    ":::"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## A Minimal Charting Application"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The `Script` function allows you to include JavaScript. You can use Python to generate parts of your JS or JSON like this:\n",
    "\n",
    "```python\n",
    "import json\n",
    "from fasthtml.common import * \n",
    "\n",
    "app, rt = fast_app(hdrs=(Script(src=\"https://cdn.plot.ly/plotly-2.32.0.min.js\"),))\n",
    "\n",
    "data = json.dumps({\n",
    "    \"data\": [{\"x\": [1, 2, 3, 4],\"type\": \"scatter\"},\n",
    "            {\"x\": [1, 2, 3, 4],\"y\": [16, 5, 11, 9],\"type\": \"scatter\"}],\n",
    "    \"title\": \"Plotly chart in FastHTML \",\n",
    "    \"description\": \"This is a demo dashboard\",\n",
    "    \"type\": \"scatter\"\n",
    "})\n",
    "\n",
    "\n",
    "@rt(\"/\")\n",
    "def get():\n",
    "  return Titled(\"Chart Demo\", Div(id=\"myDiv\"),\n",
    "    Script(f\"var data = {data}; Plotly.newPlot('myDiv', data);\"))\n",
    "\n",
    "serve()\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Debug Mode"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "When we can't figure out a bug in FastHTML, we can run it in `DEBUG` mode. When an error is thrown, the error screen is displayed in the browser. This error setting should never be used in a deployed app.\n",
    "\n",
    "```python\n",
    "from fasthtml.common import *\n",
    "\n",
    "app, rt = fast_app(debug=True)  # <1>\n",
    "\n",
    "@rt(\"/\")\n",
    "def get():\n",
    "    1/0  # <2>\n",
    "    return Titled(\"FastHTML Error!\", P(\"Let's error!\"))\n",
    "\n",
    "serve()\n",
    "```\n",
    "\n",
    "1. `debug=True` sets debug mode on. \n",
    "2. Python throws an error when it tries to divide an integer by zero."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Routing"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "FastHTML builds upon FastAPI's friendly decorator pattern for specifying URLs, with extra features:\n",
    "\n",
    "```{.python filename=\"main.py\" code-line-numbers=\"true\"}\n",
    "from fasthtml.common import * \n",
    "\n",
    "app, rt = fast_app()\n",
    "\n",
    "@rt(\"/\")  # <1>\n",
    "def get():\n",
    "  return Titled(\"FastHTML\", P(\"Let's do this!\"))\n",
    "\n",
    "@rt(\"/hello\")  # <2>\n",
    "def get():\n",
    "  return Titled(\"Hello, world!\")\n",
    "\n",
    "serve()\n",
    "```\n",
    "\n",
    "1. The \"/\" URL on line 5 is the home of a project. This would be accessed at [127.0.0.1:5001](http://127.0.0.1:5001).\n",
    "2. \"/hello\" URL on line 9 will be found by the project if the user visits [127.0.0.1:5001/hello](http://127.0.0.1:5001/hello).\n",
    "\n",
    "::: {.callout-tip}\n",
    "It looks like `get()` is being defined twice, but that's not the case. Each function decorated with `rt` is totally separate, and is injected into the router. We're not calling them in the module's  namespace (`locals()`). Rather, we're loading them into the routing mechanism using the `rt` decorator.\n",
    ":::\n",
    "\n",
    "You can do more! Read on to learn what we can do to make parts of the URL dynamic."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Variables in URLs"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You can add variable sections to a URL by marking them with `{variable_name}`. Your function then receives the `{variable_name}` as a keyword argument, but only if it is the correct type. Here's an example:\n",
    "\n",
    "```{.python filename=\"main.py\" code-line-numbers=\"true\"}\n",
    "from fasthtml.common import * \n",
    "\n",
    "app, rt = fast_app()\n",
    "\n",
    "@rt(\"/{name}/{age}\")  # <1>\n",
    "def get(name: str, age: int):  # <2>\n",
    "  return Titled(f\"Hello {name.title()}, age {age}\")  # <3>\n",
    "\n",
    "serve()\n",
    "```\n",
    "\n",
    "1. We specify two variable names, `name` and `age`.\n",
    "2. We define two function arguments named identically to the variables. You will note that we specify the Python types to be passed.\n",
    "3. We use these functions in our project.\n",
    "\n",
    "\n",
    "Try it out by going to this address: [127.0.0.1:5001/uma/5](http://127.0.0.1:5001/uma/5). You should get a page that says,\n",
    "\n",
    "> \"Hello Uma, age 5\".\n",
    "\n",
    "\n",
    "### What happens if we enter incorrect data?\n",
    "\n",
    "The [127.0.0.1:5001/uma/5](http://127.0.0.1:5001/uma/5) URL works because `5` is an integer. If we enter something that is not, such as [127.0.0.1:5001/uma/five](http://127.0.0.1:5001/uma/five), then FastHTML will return an error instead of a web page.\n",
    "\n",
    "::: {.callout-note}\n",
    "### FastHTML URL routing supports more complex types\n",
    "\n",
    "The two examples we provide here use Python's built-in `str` and `int` types, but you can use your own types, including more complex ones such as those defined by libraries like [attrs](https://pypi.org/project/attrs/), [pydantic](https://pypi.org/project/pydantic/), and even [sqlmodel](https://pypi.org/project/sqlmodel/). \n",
    ":::"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## HTTP Methods"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "FastHTML matches function names to HTTP methods. So far the URL routes we've defined have been for HTTP GET methods, the most common method for web pages.\n",
    "\n",
    "Form submissions often are sent as HTTP POST. When dealing with more dynamic web page designs, also known as Single Page Apps (SPA for short), the need can arise for other methods such as HTTP PUT and HTTP DELETE. The way FastHTML handles this is by changing the function name.\n",
    "\n",
    "```{.python filename=\"main.py\" code-line-numbers=\"true\"}\n",
    "from fasthtml.common import * \n",
    "\n",
    "app, rt = fast_app()\n",
    "\n",
    "@rt(\"/\")  \n",
    "def get(): # <1>\n",
    "  return Titled(\"HTTP GET\", P(\"Handle GET\"))\n",
    "\n",
    "@rt(\"/\")  \n",
    "def post(): # <2>\n",
    "  return Titled(\"HTTP POST\", P(\"Handle POST\"))\n",
    "\n",
    "serve()\n",
    "```\n",
    "\n",
    "1. On line 6 because the `get()` function name is used, this will handle HTTP GETs going to the `/` URI.\n",
    "2. On line 10 because the `post()` function name is used, this will handle HTTP POSTs going to the `/` URI."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## CSS Files and Inline Styles"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Here we modify default headers to demonstrate how to use the [Sakura CSS microframework](https://github.com/oxalorg/sakura) instead of FastHTML's default of Pico CSS.\n",
    "\n",
    "```{.python filename=\"main.py\" code-line-numbers=\"true\"}\n",
    "from fasthtml.common import * \n",
    "\n",
    "app, rt = fast_app(\n",
    "    pico=False,  # <1>\n",
    "    hdrs=(\n",
    "        Link(rel='stylesheet', href='assets/normalize.min.css', type='text/css'),\n",
    "        Link(rel='stylesheet', href='assets/sakura.css', type='text/css'),  # <2>\n",
    "        Style(\"p {color: red;}\")  # <3>\n",
    "))\n",
    "\n",
    "@app.get(\"/\")\n",
    "def home():\n",
    "    return Titled(\"FastHTML\",\n",
    "        P(\"Let's do this!\"),\n",
    "    )\n",
    "\n",
    "serve()\n",
    "```\n",
    "\n",
    "1. By setting `pico` to `False`, FastHTML will not include `pico.min.css`.\n",
    "2. This will generate an HTML `<link>` tag for sourcing the css for Sakura.\n",
    "3. If you want an inline styles, the `Style()` function will put the result into the HTML."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Other Static Media File Locations"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "As you saw, `Script` and `Link` are specific to the most common static media use cases in web apps: including JavaScript, CSS, and images. But it also works with videos and other static media files. The default behavior is to look for these files in the root directory - typically we don't do anything special to include them. We can change the default directory that is looked in for files by adding the `static_path` parameter to the `fast_app` function.\n",
    "\n",
    "```python\n",
    "app, rt = fast_app(static_path='public')\n",
    "```\n",
    "\n",
    "FastHTML also allows us to define a route that uses `FileResponse` to serve the file at a specified path. This is useful for serving images, videos, and other media files from a different directory without having to change the paths of many files. So if we move the directory containing the media files, we only need to change the path in one place. In the example below, we call images from a directory called `public`.\n",
    "\n",
    "```python\n",
    "@rt(\"/{fname:path}.{ext:static}\")\n",
    "async def get(fname:str, ext:str): \n",
    "    return FileResponse(f'public/{fname}.{ext}')\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Rendering Markdown"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "```python\n",
    "from fasthtml.common import *\n",
    "\n",
    "hdrs = (MarkdownJS(), HighlightJS(langs=['python', 'javascript', 'html', 'css']), )\n",
    "\n",
    "app, rt = fast_app(hdrs=hdrs)\n",
    "\n",
    "content = \"\"\"\n",
    "Here are some _markdown_ elements.\n",
    "\n",
    "- This is a list item\n",
    "- This is another list item\n",
    "- And this is a third list item\n",
    "\n",
    "**Fenced code blocks work here.**\n",
    "\"\"\"\n",
    "\n",
    "@rt('/')\n",
    "def get(req):\n",
    "    return Titled(\"Markdown rendering example\", Div(content,cls=\"marked\"))\n",
    "\n",
    "serve()\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Code highlighting"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Here's how to highlight code without any markdown configuration.\n",
    "\n",
    "```python\n",
    "from fasthtml.common import *\n",
    "\n",
    "# Add the HighlightJS built-in header\n",
    "hdrs = (HighlightJS(langs=['python', 'javascript', 'html', 'css']),)\n",
    "\n",
    "app, rt = fast_app(hdrs=hdrs)\n",
    "\n",
    "code_example = \"\"\"\n",
    "import datetime\n",
    "import time\n",
    "\n",
    "for i in range(10):\n",
    "    print(f\"{datetime.datetime.now()}\")\n",
    "    time.sleep(1)\n",
    "\"\"\"\n",
    "\n",
    "@rt('/')\n",
    "def get(req):\n",
    "    return Titled(\"Markdown rendering example\",\n",
    "        Div(\n",
    "            # The code example needs to be surrounded by\n",
    "            # Pre & Code elements\n",
    "            Pre(Code(code_example))\n",
    "    ))\n",
    "\n",
    "serve()\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Defining new `ft` components"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We can build our own `ft` components and combine them with other components. The simplest method is defining them as a function."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from fasthtml.common import *"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/markdown": [
       "```html\n",
       "<main>  <div class=\"hero\">\n",
       "    <h1>Hello World</h1>\n",
       "    <p>This is a hero statement</p>\n",
       "  </div>\n",
       "</main>\n",
       "```"
      ],
      "text/plain": [
       "main((div((h1(('Hello World',),{}), p(('This is a hero statement',),{})),{'class': 'hero'}),),{})"
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "def hero(title, statement):\n",
    "    return Div(H1(title),P(statement), cls=\"hero\")\n",
    "\n",
    "# usage example\n",
    "Main(\n",
    "    hero(\"Hello World\", \"This is a hero statement\")\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Pass through components"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "For when we need to define a new component that allows zero-to-many components to be nested within them, we lean on Python's `*args` and `**kwargs` mechanism. Useful for creating page layout controls."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/markdown": [
       "```html\n",
       "<main class=\"dashboard\">  <h1>Dashboard</h1>\n",
       "  <div>\n",
       "    <ul>\n",
       "      <li>0</li>\n",
       "      <li>1</li>\n",
       "      <li>2</li>\n",
       "    </ul>\n",
       "    <p class=\"description\">Some content</p>\n",
       "  </div>\n",
       "</main>\n",
       "```"
      ],
      "text/plain": [
       "main((h1(('Dashboard',),{}), div((ul((li((0,),{}), li((1,),{}), li((2,),{})),{}), p(('Some content',),{'class': 'description'})),{})),{'class': 'dashboard'})"
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "def layout(*args, **kwargs):\n",
    "    \"\"\"Dashboard layout for all our dashboard views\"\"\"\n",
    "    return Main(\n",
    "        H1(\"Dashboard\"),\n",
    "        Div(*args, **kwargs),\n",
    "        cls=\"dashboard\",\n",
    "    )\n",
    "\n",
    "# usage example\n",
    "layout(\n",
    "    Ul(*[Li(o) for o in range(3)]),\n",
    "    P(\"Some content\", cls=\"description\"),\n",
    ")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Dataclasses as ft components"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "While functions are easy to read, for more complex components some might find it easier to use a dataclass."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/markdown": [
       "```html\n",
       "<main>  <div class=\"hero\">\n",
       "    <h1>Hello World</h1>\n",
       "    <p>This is a hero statement</p>\n",
       "  </div>\n",
       "</main>\n",
       "```"
      ],
      "text/plain": [
       "main((Hero(title='Hello World', statement='This is a hero statement'),),{})"
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from dataclasses import dataclass\n",
    "\n",
    "@dataclass\n",
    "class Hero:\n",
    "    title: str\n",
    "    statement: str\n",
    "    \n",
    "    def __ft__(self):\n",
    "        \"\"\" The __ft__ method renders the dataclass at runtime.\"\"\"\n",
    "        return Div(H1(self.title),P(self.statement), cls=\"hero\")\n",
    "    \n",
    "# usage example\n",
    "Main(\n",
    "    Hero(\"Hello World\", \"This is a hero statement\")\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Testing views in notebooks"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Because of the ASGI event loop it is currently impossible to run FastHTML inside a notebook. However, we can still test the output of our views. To do this, we leverage Starlette, an ASGI toolkit that FastHTML uses."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      " <!doctype html>\n",
      " <html>\n",
      "   <head>\n",
      "<title>FastHTML is awesome</title>   </head>\n",
      "   <body>\n",
      "<main class=\"container\">       <h1>FastHTML is awesome</h1>\n",
      "       <p>The fastest way to create web apps in Python</p>\n",
      "</main>   </body>\n",
      " </html>\n",
      "\n"
     ]
    }
   ],
   "source": [
    "# First we instantiate our app, in this case we remove the\n",
    "# default headers to reduce the size of the output.\n",
    "app, rt = fast_app(default_hdrs=False)\n",
    "\n",
    "# Setting up the Starlette test client\n",
    "from starlette.testclient import TestClient\n",
    "client = TestClient(app)\n",
    "\n",
    "# Usage example\n",
    "@rt(\"/\")\n",
    "def get():\n",
    "    return Titled(\"FastHTML is awesome\", \n",
    "        P(\"The fastest way to create web apps in Python\"))\n",
    "\n",
    "print(client.get(\"/\").text)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Forms"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "To validate data coming from users, first define a dataclass representing the data you want to check. Here's an example representing a signup form."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from dataclasses import dataclass\n",
    "\n",
    "@dataclass\n",
    "class Profile: email:str; phone:str; age:int"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Create an FT component representing an empty version of that form. Don't pass in any value to fill the form, that gets handled later."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/markdown": [
       "```html\n",
       "<form enctype=\"multipart/form-data\" method=\"post\" action=\"/profile\"><fieldset><label>Email      <input name=\"email\">\n",
       "</label><label>Phone      <input name=\"phone\">\n",
       "</label><label>Age      <input name=\"age\">\n",
       "</label></fieldset><button type=\"submit\">Save</button></form>\n",
       "```"
      ],
      "text/plain": [
       "form((fieldset((label(('Email', input((),{'name': 'email'})),{}), label(('Phone', input((),{'name': 'phone'})),{}), label(('Age', input((),{'name': 'age'})),{})),{}), button(('Save',),{'type': 'submit'})),{'enctype': 'multipart/form-data', 'method': 'post', 'action': '/profile'})"
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "profile_form = Form(method=\"post\", action=\"/profile\")(\n",
    "        Fieldset(\n",
    "            Label('Email', Input(name=\"email\")),\n",
    "            Label(\"Phone\", Input(name=\"phone\")),\n",
    "            Label(\"Age\", Input(name=\"age\")),\n",
    "        ),\n",
    "        Button(\"Save\", type=\"submit\"),\n",
    "    )\n",
    "profile_form"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Once the dataclass and form function are completed, we can add data to the form. To do that, instantiate the profile dataclass:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Profile(email='john@example.com', phone='123456789', age=5)"
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "profile = Profile(email='john@example.com', phone='123456789', age=5)\n",
    "profile"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Then add that data to the `profile_form` using FastHTML's `fill_form` class:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/markdown": [
       "```html\n",
       "<form enctype=\"multipart/form-data\" method=\"post\" action=\"/profile\"><fieldset><label>Email      <input name=\"email\" value=\"john@example.com\">\n",
       "</label><label>Phone      <input name=\"phone\" value=\"123456789\">\n",
       "</label><label>Age      <input name=\"age\" value=\"5\">\n",
       "</label></fieldset><button type=\"submit\">Save</button></form>\n",
       "```"
      ],
      "text/plain": [
       "form((fieldset((label(('Email', input((),{'name': 'email', 'value': 'john@example.com'})),{}), label(('Phone', input((),{'name': 'phone', 'value': '123456789'})),{}), label(('Age', input((),{'name': 'age', 'value': 5})),{})),{}), button(('Save',),{'type': 'submit'})),{'enctype': 'multipart/form-data', 'method': 'post', 'action': '/profile'})"
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "fill_form(profile_form, profile)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Forms with views"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The usefulness of FastHTML forms becomes more apparent when they are combined with FastHTML views. We'll show how this works by using the test client from above. First, let's create a SQlite database:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#| hide\n",
    "from pathlib import Path\n",
    "if Path(\"profiles.db\").exists():\n",
    "    Path(\"profiles.db\").unlink()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "db = database(\"profiles.db\")\n",
    "profiles = db.create(Profile, pk=\"email\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now we insert a record into the database:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Profile(email='john@example.com', phone='123456789', age=5)"
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "profiles.insert(profile)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "And we can then demonstrate in the code that form is filled and displayed to the user."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      " <!doctype html>\n",
      " <html>\n",
      "   <head>\n",
      "<title>Profile for john@example.com</title>   </head>\n",
      "   <body>\n",
      "<main class=\"container\">       <h1>Profile for john@example.com</h1>\n",
      "<form enctype=\"multipart/form-data\" method=\"post\" action=\"/profile\"><fieldset><label>Email             <input name=\"email\" value=\"john@example.com\">\n",
      "</label><label>Phone             <input name=\"phone\" value=\"123456789\">\n",
      "</label><label>Age             <input name=\"age\" value=\"5\">\n",
      "</label></fieldset><button type=\"submit\">Save</button></form></main>   </body>\n",
      " </html>\n",
      "\n"
     ]
    }
   ],
   "source": [
    "@rt(\"/profile/{email}\")\n",
    "def profile(email:str):\n",
    "    profile = profiles[email]  # <1>\n",
    "    filled_profile_form = fill_form(profile_form, profile) # <2>\n",
    "    return Titled(f'Profile for {profile.email}', filled_profile_form)\n",
    "\n",
    "print(client.get(f\"/profile/john@example.com\").text)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "1. Fetch the profile using the profile table's `email` primary key \n",
    "2. Fill the form for display."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "And now let's demonstrate making a change to the data. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      " <!doctype html>\n",
      " <html>\n",
      "   <head>\n",
      "<title>Profile for john@example.com</title>   </head>\n",
      "   <body>\n",
      "<main class=\"container\">       <h1>Profile for john@example.com</h1>\n",
      "<form enctype=\"multipart/form-data\" method=\"post\" action=\"/profile\"><fieldset><label>Email             <input name=\"email\" value=\"john@example.com\">\n",
      "</label><label>Phone             <input name=\"phone\" value=\"7654321\">\n",
      "</label><label>Age             <input name=\"age\" value=\"25\">\n",
      "</label></fieldset><button type=\"submit\">Save</button></form></main>   </body>\n",
      " </html>\n",
      "\n"
     ]
    }
   ],
   "source": [
    "@rt(\"/profile\")\n",
    "def post(profile: Profile): # <1>\n",
    "    profiles.update(profile) # <2>\n",
    "    return RedirectResponse(url=f\"/profile/{profile.email}\") # <3>\n",
    "\n",
    "new_data = dict(email='john@example.com', phone='7654321', age=25)\n",
    "print(client.post(\"/profile\", data=new_data).text)  # <4>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "1. We use the `Profile` dataclass definition to set the type for the incoming `profile` content. This validates the field types for the incoming data\n",
    "2. Taking our validated data, we updated the profiles table\n",
    "3. We redirect the user back to their profile view\n",
    "4. The display is of the profile form view showing the changes in data. "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Strings and conversion order"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The general rules for rendering are: \n",
    "- `__ft__` method will be called (for default components like `P`, `H2`, etc. or if you define your own components)\n",
    "- If you pass a string, it will be escaped\n",
    "- On other python objects, `str()` will be called\n",
    "\n",
    "As a consequence, if you want to include plain HTML tags directly into e.g. a `Div()` they will get escaped by default (as a security measure to avoid code injections). This can be avoided by using `NotStr()`, a convenient way to reuse python code that returns already HTML. If you use pandas, you can use `pandas.DataFrame.to_html()` to get a nice table. To include the output a FastHTML, wrap it in `NotStr()`, like `Div(NotStr(df.to_html()))`.\n",
    "\n",
    "Above we saw how a dataclass behaves with the `__ft__` method defined. On a plain dataclass, `str()` will be called (but not escaped)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/markdown": [
       "```html\n",
       "<main>Hero(title='<h1>Hello World</h1>', statement='This is a hero statement')</main>\n",
       "```"
      ],
      "text/plain": [
       "main((Hero(title='<h1>Hello World</h1>', statement='This is a hero statement'),),{})"
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from dataclasses import dataclass\n",
    "\n",
    "@dataclass\n",
    "class Hero:\n",
    "    title: str\n",
    "    statement: str\n",
    "        \n",
    "# rendering the dataclass with the default method\n",
    "Main(\n",
    "    Hero(\"<h1>Hello World</h1>\", \"This is a hero statement\")\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/markdown": [
       "```html\n",
       "<div>Let&#x27;s include some HTML here: &lt;div&gt;Some HTML&lt;/div&gt;</div>\n",
       "\n",
       "```"
      ],
      "text/plain": [
       "div((\"Let's include some HTML here: <div>Some HTML</div>\",),{})"
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# This will display the HTML as text on your page\n",
    "Div(\"Let's include some HTML here: <div>Some HTML</div>\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/markdown": [
       "```html\n",
       "<div><div><h1>Some HTML</h1></div></div>\n",
       "\n",
       "```"
      ],
      "text/plain": [
       "div(('<div><h1>Some HTML</h1></div>',),{})"
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Keep the string untouched, will be rendered on the page\n",
    "Div(NotStr(\"<div><h1>Some HTML</h1></div>\"))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Custom exception handlers"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "FastHTML allows customization of exception handlers, but does so gracefully. What this means is by default it includes all the `<html>` tags needed to display attractive content. Try it out!\n",
    "\n",
    "```python\n",
    "from fasthtml.common import *\n",
    "\n",
    "def not_found(req, exc): return Titled(\"404: I don't exist!\")\n",
    "\n",
    "exception_handlers = {404: not_found}\n",
    "\n",
    "app, rt = fast_app(exception_handlers=exception_handlers)\n",
    "\n",
    "@rt('/')\n",
    "def get():\n",
    "    return (Titled(\"Home page\", P(A(href=\"/oops\")(\"Click to generate 404 error\"))))\n",
    "\n",
    "serve()\n",
    "```\n",
    "\n",
    "We can also use lambda to make things more terse:\n",
    "\n",
    "```python\n",
    "from fasthtml.common import *\n",
    "\n",
    "exception_handlers={\n",
    "    404: lambda req, exc: Titled(\"404: I don't exist!\"),\n",
    "    418: lambda req, exc: Titled(\"418: I'm a teapot!\")\n",
    "}\n",
    "\n",
    "app, rt = fast_app(exception_handlers=exception_handlers)\n",
    "\n",
    "@rt('/')\n",
    "def get():\n",
    "    return (Titled(\"Home page\", P(A(href=\"/oops\")(\"Click to generate 404 error\"))))\n",
    "\n",
    "serve()\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Cookies"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We can set cookies using the `cookie()` function. In our example, we'll create a `timestamp` cookie."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from datetime import datetime\n",
    "from IPython.display import HTML"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       " <!doctype html>\n",
       " <html>\n",
       "   <head>\n",
       "<title>FastHTML page</title>   </head>\n",
       "   <body>\n",
       "     <p>Set to 2024-09-26 15:33:48.141869</p>\n",
       "   </body>\n",
       " </html>\n"
      ],
      "text/plain": [
       "<IPython.core.display.HTML object>"
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "@rt(\"/settimestamp\")\n",
    "def get(req):\n",
    "    now = datetime.now()\n",
    "    return P(f'Set to {now}'), cookie('now', datetime.now())\n",
    "\n",
    "HTML(client.get('/settimestamp').text)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now let's get it back using the same name for our parameter as the cookie name."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'Cookie was set at time 15:33:48.141903'"
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "@rt('/gettimestamp')\n",
    "def get(now:parsed_date): return f'Cookie was set at time {now.time()}'\n",
    "\n",
    "client.get('/gettimestamp').text"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Sessions"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "For convenience and security, FastHTML has a mechanism for storing small amounts of data in the user's browser. We can do this by adding a `session` argument to routes. FastHTML sessions are Python dictionaries, and we can leverage to our benefit. The example below shows how to concisely set and get sessions."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "@rt('/adder/{num}')\n",
    "def get(session, num: int):\n",
    "    session.setdefault('sum', 0)\n",
    "    session['sum'] = session.get('sum') + num\n",
    "    return Response(f'The sum is {session[\"sum\"]}.')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Toasts (also known as Messages)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Toasts, sometimes called \"Messages\" are small notifications usually in colored boxes used to notify users that something has happened. Toasts can be of four types:\n",
    "\n",
    "- info\n",
    "- success\n",
    "- warning\n",
    "- error\n",
    "\n",
    "Examples toasts might include:\n",
    "\n",
    "- \"Payment accepted\"\n",
    "- \"Data submitted\"\n",
    "- \"Request approved\"\n",
    "\n",
    " Toasts require the use of the `setup_toasts()` function plus every view needs these two features:\n",
    "\n",
    "- The session argument\n",
    "- Must return FT components\n",
    "\n",
    "```python\n",
    "setup_toasts(app) # <1>\n",
    "\n",
    "@rt('/toasting')\n",
    "def get(session):  # <2>\n",
    "    # Normally one toast is enough, this allows us to see\n",
    "    # different toast types in action.\n",
    "    add_toast(session, f\"Toast is being cooked\", \"info\")\n",
    "    add_toast(session, f\"Toast is ready\", \"success\")\n",
    "    add_toast(session, f\"Toast is getting a bit crispy\", \"warning\")\n",
    "    add_toast(session, f\"Toast is burning!\", \"error\")\n",
    "    return Titled(\"I like toast\") # <3>\n",
    "```\n",
    "\n",
    "1. `setup_toasts` is a helper function that adds toast dependencies. Usually this would be declared right after `fast_app()`\n",
    "2. Toasts require sessions\n",
    "3. Views with Toasts must return FT or FtResponse components.\n",
    "\n",
    "💡 `setup_toasts` takes a `duration` input that allows you to specify how long a toast will be visible before disappearing. For example `setup_toasts(duration=5)` sets the toasts duration to 5 seconds. By default toasts disappear after 10 seconds.\n",
    "\n",
    "⚠️ Toasts don't work with SPA like navigation that replaces the entire body such as this navigation trigger `A('About', hx_get=\"/about\", hx_swap=\"outerHTML\", hx_push_url=\"true\", hx_target=\"body\")`. As an alternative, wrap the content of your route in an element containing an id and set this id as the target for your navigation trigger (i.e. `hx_target='#container_id'`). "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Authentication and authorization"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In FastHTML the tasks of authentication and authorization are handled with Beforeware.  Beforeware are functions that run before the route handler is called. They are useful for global tasks like ensuring users are authenticated or have permissions to access a view.\n",
    "\n",
    "First, we write a function that accepts a request and session arguments:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Status code 303 is a redirect that can change POST to GET,\n",
    "# so it's appropriate for a login page.\n",
    "login_redir = RedirectResponse('/login', status_code=303)\n",
    "\n",
    "def user_auth_before(req, sess):\n",
    "    # The `auth` key in the request scope is automatically provided\n",
    "    # to any handler which requests it, and can not be injected\n",
    "    # by the user using query params, cookies, etc, so it should\n",
    "    # be secure to use.    \n",
    "    auth = req.scope['auth'] = sess.get('auth', None)\n",
    "    # If the session key is not there, it redirects to the login page.\n",
    "    if not auth: return login_redir"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now we pass our `user_auth_before` function as the first argument into a `Beforeware` class. We also pass a list of regular expressions to the `skip` argument, designed to allow users to still get to the home and login pages."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "beforeware = Beforeware(\n",
    "    user_auth_before,\n",
    "    skip=[r'/favicon\\.ico', r'/static/.*', r'.*\\.css', r'.*\\.js', '/login', '/']\n",
    ")\n",
    "\n",
    "app, rt = fast_app(before=beforeware)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Server-sent events (SSE)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    "With [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events), it's possible for a server to send new data to a web page at any time, by pushing messages to the web page. Unlike WebSockets, SSE can only go in one direction: server to client. SSE is also part of the HTTP specification unlike WebSockets which uses its own specification. \n",
    "\n",
    "FastHTML introduces several tools for working with SSE which are covered in the example below. While concise, there's a lot going on in this function so we've annotated it quite a bit."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import random\n",
    "from asyncio import sleep\n",
    "from fasthtml.common import *\n",
    "\n",
    "hdrs=(Script(src=\"https://unpkg.com/htmx-ext-sse@2.2.1/sse.js\"),) # <1>\n",
    "app,rt = fast_app(hdrs=hdrs)\n",
    "\n",
    "@rt\n",
    "def index():\n",
    "    return Titled(\"SSE Random Number Generator\",\n",
    "        P(\"Generate pairs of random numbers, as the list grows scroll downwards.\"),\n",
    "        Div(hx_ext=\"sse\", # <2>\n",
    "            sse_connect=\"/number-stream\", # <3>\n",
    "            hx_swap=\"beforeend show:bottom\", # <4>\n",
    "            sse_swap=\"message\")) # <5>\n",
    "\n",
    "shutdown_event = signal_shutdown() # <6>\n",
    "\n",
    "async def number_generator(): # <7>\n",
    "    while not shutdown_event.is_set(): # <8>\n",
    "        data = Article(random.randint(1, 100))\n",
    "        yield sse_message(data)  # <9>\n",
    "        await sleep(1)\n",
    "\n",
    "@rt(\"/number-stream\")\n",
    "async def get(): return EventStream(number_generator()) # <10>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "1. Import the HTMX SSE extension \n",
    "2. Tell HTMX to load the SSE extension\n",
    "3. Look at the `/number-stream` endpoint for SSE content\n",
    "4. When new items come in from the SSE endpoint, add them at the end of the current content within the div. If they go beyond the screen, scroll downwards\n",
    "5. Specify the name of the event. FastHTML's default event name is \"message\". Only change if you have more than one call to SSE endpoints within a view\n",
    "6. Set up the asyncio event loop\n",
    "7. Don't forget to make this an `async` function!\n",
    "8. Iterate through the asyncio event loop\n",
    "9. We yield the data. Data ideally should be comprised of FT components as that plugs nicely into HTMX in the browser\n",
    "10. The endpoint view needs to be an async function that returns a `EventStream`\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Websockets"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "With websockets we can have bi-directional communications between a browser and client. Websockets are useful for things like chat and certain types of games. While websockets can be used for single direction messages from the server (i.e. telling users that a process is finished), that task is arguably better suited for SSE.\n",
    "\n",
    "FastHTML provides useful tools for adding websockets to your pages."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from fasthtml.common import *\n",
    "from asyncio import sleep\n",
    "\n",
    "app, rt = fast_app(exts='ws') # <1>\n",
    "\n",
    "def mk_inp(): return Input(id='msg', autofocus=True) # <2>\n",
    "\n",
    "@rt('/')\n",
    "async def get(request):\n",
    "    cts = Div(\n",
    "        Div(id='notifications'),\n",
    "        Form(mk_inp(), id='form', ws_send=True), # <3>\n",
    "        hx_ext='ws', ws_connect='/ws') # <4>\n",
    "    return Titled('Websocket Test', cts)\n",
    "\n",
    "async def on_connect(send): # <5>\n",
    "    print('Connected!')\n",
    "    await send(Div('Hello, you have connected', id=\"notifications\")) # <6>\n",
    "\n",
    "async def on_disconnect(ws): # <7>\n",
    "    print('Disconnected!')\n",
    "\n",
    "@app.ws('/ws', conn=on_connect, disconn=on_disconnect) # <8>\n",
    "async def ws(msg:str, send): # <9>\n",
    "    await send(Div('Hello ' + msg, id=\"notifications\")) # <10>\n",
    "    await sleep(2)\n",
    "    return Div('Goodbye ' + msg, id=\"notifications\"), mk_inp() # <11>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "1. To use websockets in FastHTML, you must instantiate the app with `exts` set to 'ws'\n",
    "2. As we want to use websockets to reset the form, we define the `mk_input` function that can be called from multiple locations\n",
    "3. We create the form and mark it with the `ws_send` attribute, which is documented here in the [HTMX websocket specification](https://v1.htmx.org/extensions/web-sockets/). This tells HTMX to send a message to the nearest websocket based on the trigger for the form element, which for forms is pressing the `enter` key, an action considered to be a form submission\n",
    "4. This is where the HTMX extension is loaded (`hx_ext='ws'`) and the nearest websocket is defined (`ws_connect='/ws'`)\n",
    "5. When a websocket first connects we can optionally have it call a function that accepts a `send` argument. The `send` argument will push a message to the browser.\n",
    "6. Here we use the `send` function that was passed into the `on_connect` function to send a `Div` with an `id` of `notifications` that HTMX assigns to the element in the page that already has an `id` of `notifications`\n",
    "7. When a websocket disconnects we can call a function which takes no arguments. Typically the role of this function is to notify the server to take an action. In this case, we print a simple message to the console\n",
    "8. We use the `app.ws` decorator to mark that `/ws` is the route for our websocket. We also pass in the two optional `conn` and `disconn` parameters to this decorator. As a fun experiment, remove the `conn` and `disconn` arguments and see what happens\n",
    "9. Define the `ws` function as async. This is necessary for ASGI to be able to serve websockets. The function accepts two arguments, a `msg` that is user input from the browser, and a `send` function for pushing data back to the browser\n",
    "10. The `send` function is used here to send HTML back to the page. As the HTML has an `id` of `notifications`, HTMX will overwrite what is already on the page with the same ID\n",
    "11. The websocket function can also be used to return a value. In this case, it is a tuple of two HTML elements. HTMX will take the elements and replace them where appropriate. As both have `id` specified (`notifications` and `msg` respectively), they will replace their predecessor on the page."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## File Uploads"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A common task in web development is uploading files. The examples below are for uploading files to the hosting server, with information about the uploaded file presented to the user.\n",
    "\n",
    ":::{.callout-warning title='File uploads in production can be dangerous'}\n",
    "File uploads can be the target of abuse, accidental or intentional. That means users may attempt to upload files that are too large or present a security risk. This is especially of concern for public facing apps. File upload security is outside the scope of this tutorial, for now we suggest reading the [OWASP File Upload Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/File_Upload_Cheat_Sheet.html).\n",
    ":::"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Single File Uploads"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "```python\n",
    "from fasthtml.common import *\n",
    "from pathlib import Path\n",
    "\n",
    "app, rt = fast_app()\n",
    "\n",
    "upload_dir = Path(\"filez\")\n",
    "upload_dir.mkdir(exist_ok=True)\n",
    "\n",
    "@rt('/')\n",
    "def get():\n",
    "    return Titled(\"File Upload Demo\",\n",
    "        Article(\n",
    "            Form(hx_post=upload, hx_target=\"#result-one\")( # <1>\n",
    "                Input(type=\"file\", name=\"file\"), # <2>\n",
    "                Button(\"Upload\", type=\"submit\", cls='secondary'),\n",
    "            ),\n",
    "            Div(id=\"result-one\")\n",
    "        )\n",
    "    )\n",
    "\n",
    "def FileMetaDataCard(file):\n",
    "    return Article(\n",
    "        Header(H3(file.filename)),\n",
    "        Ul(\n",
    "            Li('Size: ', file.size),            \n",
    "            Li('Content Type: ', file.content_type),\n",
    "            Li('Headers: ', file.headers),\n",
    "        )\n",
    "    )    \n",
    "\n",
    "@rt\n",
    "async def upload(file: UploadFile): # <3>\n",
    "    card = FileMetaDataCard(file)  # <4>\n",
    "    filebuffer = await file.read()  # <5>\n",
    "    (upload_dir / file.filename).write_bytes(filebuffer) # <6>\n",
    "    return card\n",
    "\n",
    "serve()\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "1. Every form rendered with the `Form` FT component defaults to `enctype=\"multipart/form-data\"`\n",
    "2. Don't forget to set the `Input` FT Component's type to `file`\n",
    "3. The upload view should receive a [Starlette UploadFile](https://www.starlette.io/requests/#request-files) type. You can add other form variables\n",
    "4. We can access the metadata of the card (filename, size, content_type, headers), a quick and safe process. We set that to the card variable\n",
    "5. In order to access the contents contained within a file we use the `await` method to read() it. As files may be quite large or contain bad data, this is a seperate step from accessing metadata\n",
    "6. This step shows how to use Python's built-in `pathlib.Path` library to write the file to disk."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Multiple File Uploads"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "```python\n",
    "from fasthtml.common import *\n",
    "from pathlib import Path\n",
    "\n",
    "app, rt = fast_app()\n",
    "\n",
    "upload_dir = Path(\"filez\")\n",
    "upload_dir.mkdir(exist_ok=True)\n",
    "\n",
    "@rt('/')\n",
    "def get():\n",
    "    return Titled(\"Multiple File Upload Demo\",\n",
    "        Article(\n",
    "            Form(hx_post=upload_many, hx_target=\"#result-many\")( # <1>\n",
    "                Input(type=\"file\", name=\"files\", multiple=True), # <2>\n",
    "                Button(\"Upload\", type=\"submit\", cls='secondary'),\n",
    "            ),\n",
    "            Div(id=\"result-many\")\n",
    "        )\n",
    "    )\n",
    "\n",
    "def FileMetaDataCard(file):\n",
    "    return Article(\n",
    "        Header(H3(file.filename)),\n",
    "        Ul(\n",
    "            Li('Size: ', file.size),            \n",
    "            Li('Content Type: ', file.content_type),\n",
    "            Li('Headers: ', file.headers),\n",
    "        )\n",
    "    )    \n",
    "\n",
    "@rt\n",
    "async def upload_many(files: list[UploadFile]): # <3>\n",
    "    cards = []\n",
    "    for file in files:  # <4>\n",
    "        cards.append(FileMetaDataCard(file))  # <5>\n",
    "        filebuffer = await file.read()  # <6>\n",
    "        (upload_dir / file.filename).write_bytes(filebuffer) # <7>\n",
    "    return cards\n",
    "\n",
    "serve()\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "1. Every form rendered with the `Form` FT component defaults to `enctype=\"multipart/form-data\"`\n",
    "2. Don't forget to set the `Input` FT Component's type to `file` and assign the multiple attribute to `True`\n",
    "3. The upload view should receive a `list` containing the [Starlette UploadFile](https://www.starlette.io/requests/#request-files) type. You can add other form variables\n",
    "4. Iterate through the files\n",
    "5. We can access the metadata of the card (filename, size, content_type, headers), a quick and safe process. We add that to the cards variable\n",
    "6. In order to access the contents contained within a file we use the `await` method to read() it. As files may be quite large or contain bad data, this is a seperate step from accessing metadata\n",
    "7. This step shows how to use Python's built-in `pathlib.Path` library to write the file to disk."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "python",
   "language": "python",
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
